 var app = getApp();
var ApiUrl = app.globalData.ApiUrl;
var mph = require("../../utils/util.js");
Page({
  /**
   * 页面的初始数据 
   */
  data: {     
    box_bg_true:false,
    hideboxblien:false, 
    hideboxblien_:false,  
    showLoading: true,
    wx:'',
    yue:'checked',
    yue_bool:true,
    password:'',
    scrollHeight: 0,
    scrollTop: 0,
    address_data:null,//地址
    address_api:{},
    adressInfoDataList:[],
    cart_datalis:[],
    total_limit: 0,
    total_limit_num: 0,
    subtract_res: 0,
    step1: [],//总数据
    cart_id: [],//购买参数
    store_cart_list:[],//商品列表
    voucher_list:[],//优惠券
    goods_flag:'',//商品券字段,传值
    goods_gift_flag:'',//礼券字段,传值
    vouchers:[],//下单时选择的券,优惠券
    voucher_info:[],//优惠券展示
    ifcart:0,
    strData:'',
    flags:'',
    pay_sn:'',
    points:0,
    psn:'',//识别参团,获取团信息
    pay_type:'wxpay_jsapi',
    pay_state:0,
    submit_bool:false,//防止重复提交
    ability:1,
    btntxt:[{
        name:'优惠券',
        num:0
    }, {
        name: '商品券',
        num: 0
      }, {
        name: '商品礼券',
        num: 0
      }
    ],
    // btntxt: ['优惠券', '商品券','商品礼券'],
    btnlistind:0,
    tijiaoBtn:false,//==================》多
    goods_freight_res:0,//运费
    order_amount_num:0,
    zhanshitxt:'可抵扣现金',
    v_price:0,
    pd_voucher_list_arr:[],
    zhanshitxt_num:0,
    voucher_price_arr:[],
    voucher_arr:[

    ],
    store_final_total_list:{},
    zdyindex:0,
    resData:0,
    num_voucher_price_arr:0,
    num_store_final_total_list:0,
    zdygoodsId:''
  },
  getvip(){
    let that = this;
    //获得我的信息
    var url = 'index.php?act=member_index';
    mph.postRequest(url, {}, function (res) {
      console.log('我的商城:==>', res.data.datas.member_info);
      if (res.data.code == 200) {
        that.setData({
          user_info: res.data.datas.member_info
        })
      } else {
        mph.showErrorTost(res.msg);
      }
    })
  },
  aaa(){},
  go_memberVIP(){
    wx.navigateTo({
      url: '/pages/memberVIP/memberVIP'
    })
  },
  box_bg_hide() {
    this.setData({
      box_bg_true: false
    })
  },
  box_bg_show() {
    this.setData({
      box_bg_true: true
    })
  },
  //使用优惠方式
  showquan:function(e){
    let index = e.currentTarget.dataset.index;
    console.log(e,123, index);
    this.setData({
      hideboxblien: true,
      zdyindex: index
    })
    this.setvoucher_list_data(this.data.btnlistind);
  },
  hideBtncont:function(){
    this.setData({
      hideboxblien:false
    })
  },
  create_coupon_ok:function(){
    this.setData({
      hideboxblien:false
    })
  },
  /** 切换优惠券
  */
  btnlist(e){//=====================================》多
    var that =this;var list = [];
    let ind = e.currentTarget.dataset.ind;

    this.setData({
        vouchers:[],
        goods_flag:[],
        goods_gift_flag:[],
        voucher_info:[]
    })
  that.setvoucher_list_data(ind);
  },
  setvoucher_list_data:function(ind){
    var that = this;
    var list = [];
    if(ind==0){//优惠券
      list = that.data.step1.voucher_list
    }
    if(ind==1){//商品券
       list = that.data.step1.other_voucher.goods_vou_list
    }
    if(ind==2){//商品礼券
       list = that.data.step1.other_voucher.gift_vou_list
    }
    console.log(list.length);
    that.setData({
      btnlistind: ind,
      voucher_list:list
    })
  },
  //选择生成商品礼券
  create_coupon: function () {
    console.log(123);
    this.setData({
      hideboxblien_: true
    })
  },
  hideBtncont_: function () {
    this.setData({
      hideboxblien_: false
    })
  },
  create_coupon_ok_: function () {
    this.setData({
      hideboxblien_: false
    })
  },
  /** 单选，选择生成商品礼券 */
  creat_lipinquanChange(e) {
    var data = e.currentTarget.dataset;
    // if (this.data.yue == '') {
    //   this.is_yue_pass();
    // } else {
    //   this.setData({
    //     yue: '',
    //     wx: 'checked'
    //   })
    // }

  },
  /** 单选，选择支付方式 */
  allCheckboxChange(e){
    var data = e.currentTarget.dataset;
    if(this.data.yue==''){
    	this.is_yue_pass();
    }else{
       this.setData({
        yue : '',
        wx : 'checked'
      })
    }
    
  },
  /** 验证是否设置支付密码
  */	
  is_yue_pass:function(){
  	var that = this
  	var url = "index.php?act=member_account&op=get_paypwd_info";
	      mph.postRequest(url,{},function (res) {
	        if(res.data.code == 200) {
            console.log('验证是否设置支付密码:====>',res.data.datas.state);
              that.setData({
                  yue: 'checked',
                  wx: '',
                  yue_bool:res.data.datas.state
            })
	        }
	      })
  },
  go_list_of_commodities(){
    wx.navigateTo({
      url: '../../pages/list_of_commodities/list_of_commodities'
    })
  },
  go_my_balance(){
    wx.navigateTo({
      url: '../../pages/my_balance/my_balance'
    })
  },

  addtilenum: function () {
    var that = this;
    let btntxt = that.data.btntxt;

    for (var n in that.data.store_cart_list) {
      let arr = [];
      let obj = that.data.store_cart_list[n].store_voucher_list;
      console.log(77777777,obj)
      for (var name in obj){
        arr.push(obj[name]);
      }
      console.log(88888,arr)
      that.data.voucher_arr.push(arr);
    }


    // function getJsonLength(jsonData) {
    //   var length;
    //   for (var ever in jsonData) {
    //     length++;
    //   }
    //   return length;
    // }

    console.log(8989898, that.data.voucher_arr, 8989898, that.data.store_cart_list);
    //优惠券
      // btntxt[0].num = that.data.step1.voucher_list.length;
    
    //商品券
    btntxt[1].num = that.data.step1.other_voucher.goods_vou_list.length;
  
    //商品礼券
    btntxt[2].num = that.data.step1.other_voucher.gift_vou_list.length;
    
    that.setData({
      btntxt: btntxt,
      voucher_arr: that.data.voucher_arr
    })
    // console.log(that.data.step1.other_voucher.goods_vou_list)
  },
  onShow:function(){
    this.is_yue_pass();
  },
  /**
   * 监听载入
   */
  onLoad: function (options) {
    console.log('userinfo')
    this.is_yue_pass();
    this.getvip();
    var that = this;
    // that.addRes();
    console.log('order',options)
    if (options.psn){//识别参团
      that.setData({
        psn:options.psn,
        zdygoodsId:options.goodsId
      });
      }
      /**立即购买 */
      if(options.type == 'only'){
        var cart_id = options.goodsId + '|' + options.buynum;
        that.setData({
            cart_id: cart_id
        })
      }else{
        var cartlist = wx.getStorageSync('shopping_cart_datalist');
        var cart_id = '';

        for (let i = 0; i < cartlist.length; i++) {
          for (let j = 0; j < cartlist[i].goods.length; j++) {
            if (cartlist[i].goods[j].checked == true){
              cart_id += cartlist[i].goods[j].cart_id + '|' + cartlist[i].goods[j].goods_num + ',';
            }
          }
        }
        // for(var i=0;i<cartlist.length;i++){
        //    cart_id += cartlist[i].cart_id + '|' + cartlist[i].goods_num+',';
        // }

        cart_id = cart_id.substr(0, cart_id.length - 1);

        that.setData({
            cart_id: cart_id,
            ifcart:1
        })
      }
    that.buy_step1();
  },


  //立即购买第一步 index.php?act=member_buy&op=buy_step1
  /** 
   * 获取商品相关数据
   */
  buy_step1:function() {
    var that = this;
    console.log(8899, that.data.cart_id, that.data.ifcart)
    var url = '/index.php?act=member_buy&op=buy_step1';
    mph.postRequest(url, {
      cart_id: that.data.cart_id,
      ifcart: that.data.ifcart},
       function (res) {
        console.log(333,res)
         let json = res.data.datas.store_final_total_list;
         let store_cart_lists = res.data.datas.store_cart_list; //
         let arr = [];
        //  let store_final_total_list_arr = [];
        //  for (var attr in json) {
        //    store_final_total_list_arr.push(json[attr]);
        //  }
        //  for (var attr in store_cart_lists) {
        //    store_final_total_list_arr.push(json[attr]);
        //  }
        //  for (let i = 0; i < store_cart_lists.length;i++){
        //    let json = store_cart_lists[i].store_voucher_list;
        //    arr.push(json);
        // }

         if (res.data.code == 200) {//
           that.setData({
             step1: res.data.datas,
             address_data: res.data.datas.address_info,
             store_cart_list: store_cart_lists,
             address_api: res.data.datas.address_api,
             tijiaoBtn:true,
             pd_voucher_list_arr: arr,
             store_final_total_list: json
           })
          //  console.log(store_final_total_list_arr, 9090, arr);
          //  that.add_points();
           that.addtilenum();

           that.addRes();
          //  that.pd_voucher_list(arr);
        }
    })
  },
  //立即购买第二步，下单 index.php?act=member_buy&op=buy_step2
  /** 
   * 获取商品相关数据
   */
  buy_step2: function () {
    var that = this;
    var data = that.data;

    wx.setStorageSync('order_parameter', data);

      console.log('系统变量',data);
    if (this.data.tijiaoBtn) {
      that.go_to_order();
    }
  },
 
  /** 函数获取地址列表
  */
  get_addr_list:function(){
    var that = this;
    var url = 'index.php?act=member_address&op=address_list';
    mph.postRequest(url, {},
      function (res) {
        if (res.data.code == 200) {
          console.log('函数获取地址列表==>',res);
          that.setData({
            adressInfoDataList: res.data.datas.address_list,
            ability:2
          })
        }
      })
  },
  /** 从新选择地址
  */
  radioChange:function(e){
      var data = e.currentTarget.dataset
      var that = this;
    var url = 'index.php?act=member_buy&op=change_address';
    mph.postRequest(url, {
      freight_hash:that.data.step1.freight_hash,
      city_id:data.param.city_id,
      area_id:data.param.area_id
    },
      function (res) {
        if (res.data.code == 200) {
          console.log(123123,res)
          that.setData({
            address_data:data.param,
            address_api:res.data.datas,
            ability:1
          });
        }
      })

  },
  //跳到添加,修改
  up_addr:function(e){    
      let id = e.currentTarget.dataset.id;
      var idv = '';
      if(id){
          idv = '?id='+id;
      }
      wx.navigateTo({
        url: '../add_address/add_address'+idv
      })
  },
  //输入密码,记录密码内容
    // getInput:function(e){
    //     this.setData({
    //       password: e.detail.value
    //     })
    // },
    //跳转到订单列表页面//+ '&&order_id=' + order_id
    go_to_order:function(){
    	wx.redirectTo({
        url: '/pages/order_detail/order_detail?yue=' + this.data.yue + '&zdygoodsId=' + this.data.zdygoodsId
      })
    },
   pd_voucher_list(obj) {//判断订单里面是否有优惠券
      var that = this;
      let v_info = obj[0].store_voucher_info;
     if (v_info) {
       console.log('判断订单里面是否有优惠券:==111===>', obj);
            that.data.voucher_info = [v_info];
          if (v_info.voucher_price) {
              that.data.v_price = v_info.voucher_price;
              let str = (v_info.voucher_price).toFixed(2);
              that.setData({
                voucher_info: that.data.voucher_info,
                v_price: that.data.v_price,
                voucher_price_i: str
              });
            } else {
              that.setData({
                voucher_price_i: '暂无可用优惠'
              });
            }

        }

    },
    /** 优惠券,商品券,礼券使用
    */
    onUsevou:function(e){
        var that = this;
        let price = e.currentTarget.dataset.price;
        let t_id = e.currentTarget.dataset.t_id;
        let store_id = e.currentTarget.dataset.store_id;
        // var info =  that.data.voucher_list[id];
        // var voucher_info =  [info];
      //  var v = info.voucher_t_id+'|'+info.voucher_store_id+'|'+info.voucher_price;
        var v = t_id + '|' + store_id + '|' + price;

      console.log('优惠券,商品券,礼券使用:==>', e,v);

      if (price) {
        let str =  parseFloat(price).toFixed(2);
        let json = {
          store_id: store_id,
          price: str
        }
        if (that.data.voucher_price_arr.length>0) {
          for (let i = 0; i < that.data.voucher_price_arr.length; i++) {
            if (that.data.voucher_price_arr[i].store_id == json.store_id) {
              that.data.voucher_price_arr[i].price = json.price; 
            }else{
              that.data.voucher_price_arr.push(json);
            }
          }
        } else {
          that.data.voucher_price_arr.push(json);
        }

        that.addRes();

        that.setData({
          vouchers: v,
          // voucher_info: voucher_info,
          // vou_check: id,
          hideboxblien: false,
          voucher_price_arr: that.data.voucher_price_arr
        });

      }
    },
    addRes(){
      let that = this;
      let voucher_price_arr = that.data.voucher_price_arr;
      let store_final_total_list = that.data.store_final_total_list;
      let num = that.data.num_voucher_price_arr;
      let num1 = that.data.num_store_final_total_list;
      let res = 0;
      for (var name in store_final_total_list) {
        num += parseFloat(store_final_total_list[name]);
      }
      if (voucher_price_arr.length>0) {
        for (let i = 0; i < voucher_price_arr.length; i++) {
          num1 += parseFloat(voucher_price_arr[i].price)
        }
      }else{
        num1 = 0;
      }
      
      res = num - num1 - parseFloat(that.data.step1.points_money);
      that.setData({
        resData: res
      });
      console.log(num, num1, res);
    },
    checkboxChange1:function(e){
        var that = this;
      var btnlistind = that.data.btnlistind;
      var list = e.detail.value;
      var arr = [],v = [];
      for (var i = 0; i <list.length; i++) {
            arr[i] = that.data.voucher_list[list[i]];
            v += that.data.voucher_list[list[i]].id+'|';
      };
      
      v.substring(0, v.length-1);
      if(btnlistind==1){
       that.setData({
        goods_flag:v,
        voucher_info:arr
      })
     }else if(btnlistind==2){
      that.setData({
        goods_gift_flag:v,
        voucher_info:arr
      })
    }
  }
});